package com.pf.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.pf.dto.response.CommodityRespDTO;
import com.pf.mapper.CategoryMapper;
import com.pf.mapper.CommodityMapper;
import com.pf.mapper.SalesMapper;
import com.pf.mapper.entity.Category;
import com.pf.mapper.entity.Commodity;
import com.pf.mapper.entity.Sales;
import com.pf.service.CommodityService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * @author PanFei
 * @version 1.0.0
 * @createTime 2021/7/27
 */
@Service
public class CommodityServiceImpl implements CommodityService {

    @Autowired
    private CategoryMapper categoryMapper;
    @Autowired
    private CommodityMapper commodityMapper;
    @Autowired
    private SalesMapper salesMapper;

    @Override
    public List<CommodityRespDTO> getAllCommodityList() {

        // 查询所有商品
        List<Commodity> commodities = commodityMapper.selectList(new LambdaQueryWrapper<Commodity>()
                .eq(Commodity::getIsDeleted, 0)
        );

        // 查询所有类别
        List<Category> categories = categoryMapper.selectList(new LambdaQueryWrapper<Category>()
                .eq(Category::getIsDeleted, 0)
        );
        Map<Integer, Category> categoryMaps = categories.stream().collect(Collectors.toMap(Category::getId, category -> category));

        return commodities.stream().map(item -> {
            Category category = Optional.ofNullable(categoryMaps.get(item.getCategoryId())).orElse(new Category());
            return CommodityRespDTO.builder()
                    .categoryId(category.getId())
                    .categoryCode(category.getCategoryCode())
                    .categoryName(category.getCategoryName())
                    .commodityId(item.getId())
                    .commodityName(item.getName())
                    .commodityPrice(item.getPrice())
                    .commodityStock(item.getStock())
                    .build();
        }).collect(Collectors.toList());
    }

    @Override
    public List<Sales> getAllCommoditySales() {
        return salesMapper.selectList(new LambdaQueryWrapper<Sales>()
                .eq(Sales::getIsDeleted, 0)
        );
    }
}
